﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace Synergy
{
    public partial class FormWgrk : Form
    {
        string 生产订单号 = "";
        string 生产订单行号 = "";
        string 加工顺序 = "";
        string 工序编号 = "";
        int ksrow;
        int jsrow;
        int 报工id = 0;
        DataTable dataTableGYLX = null;
        DataTable dataTableBasQuantity = null;
        DataTable dataTableCurrentStock = null;
        DataTable records11UpdateData = null;
        public FormWgrk()
        {
            InitializeComponent();
        }

        private void button刷新_Click(object sender, EventArgs e)
        {
            if (pub.是否有权限("005001"))
            {
                List报工记录();
                dataTableGYLX = 加载所有工艺路线();
                dataTableBasQuantity = 加载基础用量();
                dataTableCurrentStock = 加载现存量();
                records11UpdateData = 加载材料出库单子表需要的数据();
            }
            else
            {
                MessageBox.Show("您未得到该授权", "提示", MessageBoxButtons.OK);
            }
        }
       
        private void List报工记录()
        {
            string sql;
            ///最大顺序号的报工单，未入库的
            sql = @"  select id,生产订单号, 生产订单行号, 物料编号,inventory.cinvname 物料名称, 订单数量, 加工顺序, 工序编号, 工序名称, 报工数量, 工序单价, 
                开始时间, 结束时间, 报工工时, 工时单价, 金额, 报工人员,Z_UA_User.cuser_name 报工人员名称, 报工时间, 是否工时结算,'' 是否已检验,'' 入库单号,''出库单号,''是否关闭 
                FROM      Z_baogong join Z_UA_User  on Z_UA_User.cUSER_Id=z_baogong.报工人员 join inventory on inventory.cinvcode=Z_baogong.物料编号 
                join warehouse on warehouse.cwhcode=inventory.cDefWareHouse where 1=1  ";

            if (this.comboBox报工人员.Text != "请选择")
            {
                sql += " and Z_UA_User.cuser_name='" + this.comboBox报工人员.Text + "'";
            }
            if (this.comboBox1.Text != "请选择")
            {
                sql += " and cwhname='" + this.comboBox1.Text + "'";
            }

            if (this.dateTimePicker_ksrq.Checked)
            {
                sql += " and 报工时间>='" + this.dateTimePicker_ksrq.Value.ToString("yyyy-MM-dd") + "'";
            }
            if (this.dateTimePicker_jsrq.Checked)
            {
                sql += " and 报工时间<'" + this.dateTimePicker_jsrq.Value.AddDays(1).ToString("yyyy-MM-dd") + "'";
            }
            sql += " and 是否最大顺序='是最大顺序号'";
            // sql += " and 是否最大顺序='" + Get最大顺序号().ToString() + "'";
            sql += " order by  id asc ";
            DataTable tb = pub.U8GetTable(sql);
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            if (tb != null)
            {
                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    tb.Rows[i]["是否已检验"] = pub.Get是否已检验(tb.Rows[i]["id"].ToString());
                    tb.Rows[i]["入库单号"] = pub.Get入库单号(tb.Rows[i]["id"].ToString(), tb.Rows[i]["生产订单号"].ToString());
                    tb.Rows[i]["出库单号"] = pub.Get出库单号(tb.Rows[i]["id"].ToString());
                    //检查订单是否关闭了
                    生产订单号 = tb.Rows[i]["生产订单号"].ToString();
                    生产订单行号 = tb.Rows[i]["生产订单行号"].ToString();
                    if (Is生产订单关闭(生产订单号, 生产订单行号))
                    {
                        tb.Rows[i]["是否关闭"] = "已关闭";
                    }
                    else
                    {
                        tb.Rows[i]["是否关闭"] = "未关闭";
                    }
                }
            }
            if (checkBox未导入.Checked == true)
            {
                this.dataGridView1.DataSource = tb;

                for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
                {
                    string Lpv = dataGridView1.Rows[i].Cells["CU8入库单号"].Value.ToString();

                    if (Lpv != "")
                    {
                        dataGridView1.Rows.RemoveAt(i);
                    }
                }
                 this.dataGridView1.Refresh();
            }
            else
            {

                this.dataGridView1.DataSource = tb;
                this.dataGridView1.Refresh();
            }
        }
        private string Get最大顺序号()
        {
            string sql;
            sql = "select max(加工顺序) from View_工序明细 where 生产订单号='" + 生产订单号 + "' and 生产订单行号='" + 生产订单行号 + "' ";
            DataTable tb = pub.U8GetTable(sql);
            if (tb.Rows.Count > 0)
            {
                return tb.Rows[0][0].ToString();
            }
            else
            {
                return "0000";
            }
        }

        private string Get参考成本(string 物料)
        {
            string sql;
            sql = "select isnull(iinvsprice,0) from Inventory  where cinvcode='" + 物料 + "' ";
            DataTable tb = pub.U8GetTable(sql);
            if (tb.Rows.Count > 0)
            {
                return tb.Rows[0][0].ToString();
            }
            else
            {
                return "0";
            }
        }
        private bool Is生产订单关闭(string 生产订单号, string 生产订单行号)
        {
            string sql;
            sql = "select isnull(关闭人员,'') from View_生产订单明细 where 生产订单号='" + 生产订单号 + "' and 行号='" + 生产订单行号 + "'";
            DataTable tb = pub.U8GetTable(sql);
            if (tb.Rows.Count > 0)
            {
                if (tb.Rows[0][0].ToString() == "")
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }


        private void FormWgrk_Load(object sender, EventArgs e)
        {
            comboBox报工人员Initl();
            comboBox仓库Initl();
            //dataTableGYLX = 加载所有工艺路线();
            //dataTableBasQuantity = 加载基础用量();
            //dataTableCurrentStock = 加载现存量();
            //records11UpdateData = 加载材料出库单子表需要的数据();
        }

        private DataTable 加载材料出库单子表需要的数据()
        {
            string sql = @"select 生产订单ID,生产订单编号,产品编号,订单行号,生产令单的所有子件用料资料ID ,子件物料编号 ,工序行号 
                            from(select mom_order.MoId 生产订单ID,mom_order.MoCode 生产订单编号,mom_orderdetail.InvCode 产品编号,mom_orderdetail.SortSeq 订单行号
                            ,mom_moallocate.AllocateId 生产令单的所有子件用料资料ID ,mom_moallocate.InvCode 子件物料编号,mom_moallocate.OpSeq 工序行号  
                            from mom_order left join mom_orderdetail
                            on mom_order.MoId = mom_orderdetail.MoId
                            left join mom_moallocate
                            on mom_orderdetail.MoDId = mom_moallocate.MoDId
                            )a";
            return pub.U8GetTable(sql);
        }

        private DataTable 加载所有工艺路线()
        {
            string sqlBomID = @"select bom_bom.BomId,Inventory.cInvCode
                        from bom_parent
                        left join bom_bom on bom_parent.BomId = bom_bom.BomId
                        left join bas_part on bas_part.PartId = bom_parent.ParentId
                        left join Inventory on bas_part.InvCode = Inventory.cInvCode
                        left join ComputationUnit on Inventory.cComUnitCode = ComputationUnit.cComunitCode";
            return pub.U8GetTable(sqlBomID);
        }
        private DataTable 加载基础用量()
        {
            string sqlBomBody = @"select bom_opcomponent.BomId, bas_part.InvCode,Inventory.cInvName,Inventory.cInvAddCode,bom_opcomponent.BaseQtyN,Warehouse.cWhCode,Warehouse.cWhName, bom_opcomponentopt.WIPType
                                from bom_bom left join bom_opcomponent on bom_bom.BomId = bom_opcomponent.BomId
                                left join bas_part on bom_opcomponent.ComponentId = bas_part.PartId
                                left join bom_opcomponentopt on  bom_opcomponent.OpComponentId = bom_opcomponentopt.OptionsId           
                                left join Inventory on bas_part.InvCode = Inventory.cInvCode
                                left join ComputationUnit on Inventory.cComUnitCode = ComputationUnit.cComunitCode
                                left join Warehouse on Inventory.cDefWareHouse = Warehouse.cWhCode
                                where cWhCode = '0402' and bom_opcomponentopt.WIPType = 3";
            return pub.U8GetTable(sqlBomBody);
        }

        private DataTable 加载现存量()
        {
            string sql = "select cInvCode, sum(iQuantity) iQuantity from CurrentStock group by cInvCode";
            return pub.U8GetTable(sql);
        }
        private void comboBox仓库Initl()
        {
            string sql;
            sql = " select cwhname  from warehouse order by cwhcode ";

            DataTable tb = pub.U8GetTable(sql);
            DataRow dr = tb.NewRow();
            dr["cwhname"] = "请选择";
            tb.Rows.InsertAt(dr, 0);
            comboBox1.DataSource = tb;

            comboBox1.DisplayMember = "cwhname";
        }

        private void comboBox报工人员Initl()
        {
            string sql;
            sql = "select  cUser_Name from Z_UA_User where  bCCUser is not  null and  cdept !='系统组' order by cUser_Id  ";

            DataTable tb = pub.SysGetTable(sql);
            DataRow dr = tb.NewRow();
            dr["cUser_Name"] = "请选择";
            tb.Rows.InsertAt(dr, 0);
            comboBox报工人员.DataSource = tb;

            comboBox报工人员.DisplayMember = "cUser_Name";
        }

        private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            ksrow = e.RowIndex;
            this.checkBox选择打钩.Checked = true;
        }

        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            jsrow = e.RowIndex;
            this.checkBox选择打钩.Checked = false;
        }

        private void checkBox选择打钩_CheckedChanged(object sender, EventArgs e)
        {
            this.progressBar1.Value = 0;
            if (ksrow > jsrow)
            {
                int r;
                r = ksrow;
                ksrow = jsrow;
                jsrow = r;

            }
            try
            {
                for (int i = ksrow; i <= jsrow; i++)
                {
                    this.dataGridView1.Rows[i].Cells[1].Value = checkBox选择打钩.Checked;
                    if (this.progressBar1.Value >= 99)
                    {
                        this.progressBar1.Value = 0;
                    }
                    else
                    {
                        this.progressBar1.Value++;
                    }
                }
                this.progressBar1.Value = 100;
            }
            catch { }
        }

        private void checkBox全部打钩_CheckedChanged(object sender, EventArgs e)
        {
            this.progressBar1.Value = 0;

            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                this.dataGridView1.Rows[i].Cells[1].Value = checkBox全部打钩.Checked;
                if (this.progressBar1.Value >= 99)
                {
                    this.progressBar1.Value = 0;
                }
                else
                {
                    this.progressBar1.Value++;
                }
            }
            this.progressBar1.Value = 100;

        }

        private void button取数_Click(object sender, EventArgs e)
        {
            if (pub.是否有权限("005002"))
            {
                ///将报工数取到入库数
                ///
                int hang;
                for (int k = 0; k < this.dataGridView1.Rows.Count; k++)
                {
                    hang = k;
                    if (this.dataGridView1.Rows[hang].Cells["C选择"].Value != null)//打钩
                    {
                        if ((bool)this.dataGridView1.Rows[hang].Cells["C选择"].Value)
                        {
                            this.dataGridView1.Rows[hang].Cells["C本次入库数量"].Value = this.dataGridView1.Rows[hang].Cells["C报工数量"].Value;
                        }

                    }
                }
            }
            else
            {
                MessageBox.Show("您未得到该授权", "提示", MessageBoxButtons.OK);
            }
        }

        private void button取消取数_Click(object sender, EventArgs e)
        {
            if (pub.是否有权限("005003"))
            {
                int hang;
                for (int k = 0; k < this.dataGridView1.Rows.Count; k++)
                {
                    hang = k;
                    if (this.dataGridView1.Rows[hang].Cells["C选择"].Value != null)//打钩
                    {
                        if ((bool)this.dataGridView1.Rows[hang].Cells["C选择"].Value)
                        {
                            this.dataGridView1.Rows[hang].Cells["C本次入库数量"].Value = "";
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("您未得到该授权", "提示", MessageBoxButtons.OK);
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            decimal 本次入库数量;
            decimal 报工数量;

            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "C入库")
            {
                //if (MessageBox.Show(""))
                DataGridViewRow gr = this.dataGridView1.Rows[e.RowIndex];
                生产订单号 = gr.Cells["C生产订单号"].Value.ToString();
                生产订单行号 = gr.Cells["C生产订单行号"].Value.ToString();
                报工id = pub.ToNum(gr.Cells["Cid"].Value.ToString());
                本次入库数量 = pub.ToDecimal(gr.Cells["C本次入库数量"].Value.ToString());
                报工数量 = pub.ToDecimal(gr.Cells["C报工数量"].Value.ToString());
                if (Is生产订单关闭(生产订单号, 生产订单行号))
                {
                    //先检查是否订单行关闭
                    MessageBox.Show("该订单行已经关闭不能入库了，请与U8管理员联系处理!", "提示", MessageBoxButtons.OK);
                    return;

                }
                if (Is已经导入到U8(报工id))
                {
                    // 是否已经入库了
                    MessageBox.Show("该订单行已经生成产品入库单了，不能继续生成!", "提示", MessageBoxButtons.OK);
                    return;
                }

                if (本次入库数量 > 报工数量)
                {
                    MessageBox.Show("本次入库数量不能大于报工数量，不能生成!", "提示", MessageBoxButtons.OK);
                    return;
                }
                if (本次入库数量 <= 0)
                {
                    MessageBox.Show("本次入库数量不能小于等于零，不能生成!", "提示", MessageBoxButtons.OK);
                    return;
                }
                //可用量通过
                if (checkCurrentStock(gr.Cells["C物料编号"].Value.ToString(), 本次入库数量))
                {
                    string 入库单号 = 生成U8产品入库单(报工id, 本次入库数量);
                    string 材料出库单号 = 生成U8材料出库单(gr.Cells["C物料编号"].Value.ToString(), 本次入库数量, 生产订单号, 报工id.ToString(), 生产订单行号);
                    if (入库单号 != "")
                    {
                        this.dataGridView1.Rows[e.RowIndex].Cells["CU8入库单号"].Value = 入库单号;
                    }
                    else
                    {
                        MessageBox.Show("本次生产入库单失败!", "提示", MessageBoxButtons.OK);
                        return;
                    }
                    if (材料出库单号 != "" && !"0".Equals(材料出库单号))
                    {
                        this.dataGridView1.Rows[e.RowIndex].Cells["CU8出库单号"].Value = 材料出库单号;
                    }
                    else
                    {
                        MessageBox.Show("本次生产材料出库失败!", "提示", MessageBoxButtons.OK);
                        return;
                    }
                }
            }
        }

        private string 生成U8材料出库单(string 物料编号, decimal 入库数量, string 生产订单号, string 报工id, string 生产订单行号)
        {
            string sqlBomID = @"select bom_bom.BomId
                        from bom_parent
                        left join bom_bom on bom_parent.BomId = bom_bom.BomId
                        left join bas_part on bas_part.PartId = bom_parent.ParentId
                        left join Inventory on bas_part.InvCode = Inventory.cInvCode
                        left join ComputationUnit on Inventory.cComUnitCode = ComputationUnit.cComunitCode
                        where Inventory.cInvCode = '";
            sqlBomID += 物料编号 + "'";
            DataTable dt = pub.U8GetTable(sqlBomID);
            if (dt != null && dt.Rows.Count > 0)
            {
                string bomId = dt.Rows[0]["BomId"].ToString();//获取BOMID
                string key = "";

                string sqlBomBody = @"select bas_part.InvCode,Inventory.cInvName,Inventory.cInvAddCode,bom_opcomponent.BaseQtyN,Warehouse.cWhCode,Warehouse.cWhName
                                from bom_bom left join bom_opcomponent on bom_bom.BomId = bom_opcomponent.BomId
                                left join bas_part on bom_opcomponent.ComponentId = bas_part.PartId
                                left join Inventory on bas_part.InvCode = Inventory.cInvCode
                                left join ComputationUnit on Inventory.cComUnitCode = ComputationUnit.cComunitCode
                                left join Warehouse on Inventory.cDefWareHouse = Warehouse.cWhCode
                                where cWhCode = '0402' and bom_opcomponent.BomId = '" + bomId + "'";
                DataTable dtBomBody = pub.U8GetTable(sqlBomBody);//获取子件明细
                Dictionary<string, List<DataRow>> dic = new Dictionary<string, List<DataRow>>();
                List<string> cWhCodeList = new List<string>();
                if (dtBomBody != null && dtBomBody.Rows.Count > 0)
                {


                    //拼接XML header
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("storeout.xml");
                    XmlElement root = xmlDoc.DocumentElement;
                    //仓库编号
                    XmlElement warehousecode = (XmlElement)root.SelectSingleNode("/ufinterface/storeout/header/warehousecode");
                    warehousecode.InnerText = dtBomBody.Rows[0]["cWhCode"].ToString();
                    //日期
                    XmlElement date = (XmlElement)root.SelectSingleNode("/ufinterface/storeout/header/date");
                    date.InnerText = DateTime.Today.ToString("yyyy-MM-dd");
                    //code
                    XmlElement code = (XmlElement)root.SelectSingleNode("/ufinterface/storeout/header/code");
                    code.InnerText = Get出库单号(DateTime.Today.ToString("yyyy-MM-dd"));
                    key = code.InnerText;
                    //ordercode
                    XmlElement ordercode = (XmlElement)root.SelectSingleNode("/ufinterface/storeout/header/ordercode");
                    ordercode.InnerText = 生产订单号;
                    //define1
                    XmlElement define1 = (XmlElement)root.SelectSingleNode("/ufinterface/storeout/header/define1");
                    define1.InnerText = 报工id;
                    //拼接XML body
                    XmlElement body = (XmlElement)root.SelectSingleNode("/ufinterface/storeout/body");
                    body.RemoveAll();
                    for (int i = 0; i < dtBomBody.Rows.Count; i++)
                    {
                        XmlElement entry = xmlDoc.CreateElement("entry");
                        body.AppendChild(entry);
                        //< id >
                        XmlElement id = xmlDoc.CreateElement("id");
                        id.InnerText = (i + 1).ToString();
                        entry.AppendChild(id);
                        //< inventorycode > 
                        XmlElement inventorycode = xmlDoc.CreateElement("inventorycode");
                        inventorycode.InnerText = dtBomBody.Rows[i]["InvCode"].ToString();
                        entry.AppendChild(inventorycode);
                        // < quantity > 1
                        XmlElement quantity = xmlDoc.CreateElement("quantity");
                        quantity.InnerText = (pub.ToDecimal(dtBomBody.Rows[i]["BaseQtyN"].ToString()) * 入库数量).ToString();
                        entry.AppendChild(quantity);
                    }
                    xmlDoc.Save("111.xml");
                    //导入U8
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://47.99.159.8/U8EAI/import.asp");///这是旭乐基的eai网址
                    //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://172.16.216.45:8989/import.asp");
                    myRequest.Method = "POST";
                    myRequest.ContentType = @"text/xml;charset=utf-8";
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    xmlDoc.Save(ms);
                    byte[] bytes = ms.ToArray();
                    myRequest.ContentLength = bytes.Length;
                    System.IO.Stream s = myRequest.GetRequestStream();
                    s.Write(bytes, 0, bytes.Length);
                    s.Close();
                    System.IO.StreamReader sr = new System.IO.StreamReader(myRequest.GetResponse().GetResponseStream());
                    String retXml = sr.ReadToEnd();
                    // MessageBox.Show(retXml);
                    sr.Close();
                    string path = "材料出库单导入结果.txt";//文件存放路径，保证文件存在。
                    StreamWriter sw = new StreamWriter(path, true);
                    sw.WriteLine(retXml);
                    sw.Close();
                }
                //查出材料出库单号
                string sql = "select isnull(max(cCode), 0) cCode,ID from rdrecord11 where cCode = '" + key + "' group by ID ";
                DataTable dt1 = pub.U8GetTable(sql);
                if (dt1 != null && dt1.Rows.Count > 0)
                {
                    更新材料已领数量(dtBomBody, 生产订单号, 生产订单行号, 入库数量, dt1.Rows[0]["cCode"].ToString(), dt1.Rows[0]["ID"].ToString(), 物料编号);
                    return dt1.Rows[0]["cCode"].ToString();
                }
                return "";
            }
            return "";
        }

        private void 更新材料已领数量(DataTable dtBomBody, string 生产订单号, string 生产订单行号, decimal 入库数量, string 材料出库单号, string 材料出库ID, string 物料编号)
        {
            int r = 0;
            List<string> iMPoIdsLists = new List<string>();
            //更新材料出库单主表
            string sql = @"UPDATE rdrecord11 SET cBusCode = '" + 材料出库单号 + "' ,cPsPcode = '" + 物料编号
                            + "',cMPoCode = '" + 生产订单号 + "'WHERE ID ='" + 材料出库ID + "'";
            SqlHelper.SqlHelper.ExecuteNonQuery(sql);
            //更新材料出库单子表
            if (records11UpdateData.Rows.Count > 0)
            {
                for (int i = 0; i < dtBomBody.Rows.Count; i++)
                {
                    string sql1 = @"update rdrecords11 set cDefine22 = @cDefine22,cmocode= @cmocode,invcode= @invcode,imoseq=@imoseq,iopseq=@iopseq where ID = @ID and cInvCode = @cInvCode";
                    DataRow[] dr = records11UpdateData.Select("生产订单编号 = '" + 生产订单号 + "' and 订单行号 = '" + 生产订单行号 + "' and 子件物料编号 = '" + dtBomBody.Rows[i]["InvCode"].ToString() + "'");
                    if (dr.Length == 1)
                    {
                        iMPoIdsLists.Add(dr[0]["生产令单的所有子件用料资料ID"].ToString());
                        SqlParameter[] paras = new SqlParameter[] {
                        //new SqlParameter() {ParameterName = "@iMPoIds",Value = dr[0]["生产令单的所有子件用料资料ID"].ToString(),SqlDbType= SqlDbType.BigInt },
                        new SqlParameter() {ParameterName = "@cDefine22",Value = dr[0]["生产令单的所有子件用料资料ID"].ToString(),SqlDbType= SqlDbType.BigInt },
                        new SqlParameter() {ParameterName = "@cmocode",Value = 生产订单号,SqlDbType= SqlDbType.NVarChar },
                        new SqlParameter() {ParameterName = "@invcode",Value = 物料编号,SqlDbType= SqlDbType.NVarChar },
                        new SqlParameter() {ParameterName = "@imoseq",Value = dr[0]["订单行号"].ToString(),SqlDbType= SqlDbType.Int },
                        new SqlParameter() {ParameterName = "@iopseq",Value = dr[0]["工序行号"].ToString(),SqlDbType= SqlDbType.NVarChar },
                        new SqlParameter() {ParameterName = "@ID",Value = 材料出库ID,SqlDbType= SqlDbType.BigInt },
                        new SqlParameter() {ParameterName = "@cInvCode",Value = dtBomBody.Rows[i]["InvCode"].ToString(),SqlDbType= SqlDbType.NVarChar },
                    };
                        r = SqlHelper.SqlHelper.ExecuteNonQuery(SqlHelper.SqlHelper.ConnectionString, CommandType.Text, sql1, paras);

                    }
                    else
                    {
                        MessageBox.Show("物料子件资料为" + dr.Length + "。请检查数据");
                    }
                }
                //更新子件已用量
                if (r > 0)
                {
                    updateMoallocate(iMPoIdsLists);
                }
            }
            else
            {
                MessageBox.Show("无材料出库单资料表");
            }
        }

        private void updateMoallocate(List<string> iMPoIdsLists)
        {
            int r = 0;
            if (iMPoIdsLists.Count > 0)
            {
                for (int i = 0; i < iMPoIdsLists.Count; i++)
                {
                    string sql = @"update mom_moallocate set IssQty =(select SUM(iQuantity) 数量 from rdrecords11 where cDefine22 = '" + iMPoIdsLists[i] + "' or iMPoIds = "+ iMPoIdsLists[i] + ") where AllocateId = '" + iMPoIdsLists[i] + "'";
                    r = SqlHelper.SqlHelper.ExecuteNonQuery(sql);
                }
            }
            if (r == 0)
            {
                MessageBox.Show("更新已领数量失败");
            }
        }

        private string 生成U8产品入库单(int 报工id, decimal 本次入库数量)
        {

            string xml_FilePath = "";
            XmlDocument xmlDoc = new XmlDocument();//新建一个XML“编辑器”

            string sql;

            sql = @"select  id, 生产订单号, 生产订单行号, 物料编号, 订单数量, 加工顺序, 工序编号, 工序名称, 报工数量, 工序单价, 
                开始时间, 结束时间, 报工工时, 工时单价, 金额, 报工人员, 报工时间, 是否工时结算, 是否已经计算, 是否最大顺序 from z_baogong   ";
            sql += " where id ='" + 报工id + "'";
            DataTable tb1 = pub.U8GetTable(sql);


            xml_FilePath = "storein.xml";
            string 入库日期 = DateTime.Today.ToString("yyyy-MM-dd");
            // string 入库日期 = "2020-01-01";
            string 入库单号 = Get入库单号();
            string 仓库编号 = Get仓库编号(tb1.Rows[0]["物料编号"].ToString());
            //string 计量单位 = Get计量单位(tb1.Rows[0]["物料编号"].ToString());
            string 生产加工单号 = tb1.Rows[0]["生产订单号"].ToString();
            string 生产子表id = tb1.Rows[0]["生产订单行号"].ToString();
            string 单价 = Get参考成本(tb1.Rows[0]["物料编号"].ToString());
            xmlDoc.Load(xml_FilePath);
            XmlNode xn = xmlDoc.SelectSingleNode("ufinterface");
            XmlNodeList xnl = xn.ChildNodes;
            XmlElement xe = xmlDoc.DocumentElement; // DocumentElement 获取xml文档对象的根XmlElement.
            //head
            string strPathcode1 = string.Format("/ufinterface/storein/header/warehousecode");
            XmlElement selectXecode1 = (XmlElement)xe.SelectSingleNode(strPathcode1);
            selectXecode1.InnerText = 仓库编号;
            string strPathcode2 = string.Format("/ufinterface/storein/header/date");
            XmlElement selectXecode2 = (XmlElement)xe.SelectSingleNode(strPathcode2);
            selectXecode2.InnerText = 入库日期;
            string strPathcode3 = string.Format("/ufinterface/storein/header/code");
            XmlElement selectXecode3 = (XmlElement)xe.SelectSingleNode(strPathcode3);
            selectXecode3.InnerText = 入库单号;
            string strPathcode4 = string.Format("/ufinterface/storein/header/auditdate");
            XmlElement selectXecode4 = (XmlElement)xe.SelectSingleNode(strPathcode4);
            selectXecode4.InnerText = 入库日期;
            string strPathcode5 = string.Format("/ufinterface/storein/header/ordercode");
            XmlElement selectXecode5 = (XmlElement)xe.SelectSingleNode(strPathcode5);
            selectXecode5.InnerText = 生产加工单号;

            //body
            string strPathcode10 = string.Format("/ufinterface/storein/body/entry/inventorycode");
            XmlElement selectXecode10 = (XmlElement)xe.SelectSingleNode(strPathcode10);
            selectXecode10.InnerText = tb1.Rows[0]["物料编号"].ToString();
            string strPathcode11 = string.Format("/ufinterface/storein/body/entry/quantity");
            XmlElement selectXecode11 = (XmlElement)xe.SelectSingleNode(strPathcode11);
            selectXecode11.InnerText = 本次入库数量.ToString();
            string strPathcode1shouldquantity = string.Format("/ufinterface/storein/body/entry/shouldquantity");
            XmlElement selectXecode1shouldquantity = (XmlElement)xe.SelectSingleNode(strPathcode1shouldquantity);
            selectXecode1shouldquantity.InnerText = 本次入库数量.ToString();
            string strPathcode1cost = string.Format("/ufinterface/storein/body/entry/cost");
            XmlElement selectXecode1cost = (XmlElement)xe.SelectSingleNode(strPathcode1cost);
            selectXecode1cost.InnerText = 单价.ToString();
            string strPathcode12 = string.Format("/ufinterface/storein/body/entry/define31");
            XmlElement selectXecode12 = (XmlElement)xe.SelectSingleNode(strPathcode12);
            selectXecode12.InnerText = 报工id.ToString();

            //string define32 = string.Format("/ufinterface/storein/body/entry/define32");
            //XmlElement define32node = (XmlElement)xe.SelectSingleNode(strPathcode12);
            //define32node.InnerText = "baogong";

            string strPathcode13 = string.Format("/ufinterface/storein/body/entry/cmassunitname");
            XmlElement selectXecode13 = (XmlElement)xe.SelectSingleNode(strPathcode13);
            selectXecode13.InnerText = "";
            string strPathcode14 = string.Format("/ufinterface/storein/body/entry/subproducingid");
            XmlElement selectXecode14 = (XmlElement)xe.SelectSingleNode(strPathcode14);
            selectXecode14.InnerText = 生产子表id;

            //string strPathcode12 = string.Format("/ufinterface/storein/body/entry/cmassunitname");
            //XmlElement selectXecode12 = (XmlElement)xe.SelectSingleNode(strPathcode12);
            //selectXecode12.InnerText = 本次入库数量.ToString();
            xmlDoc.Save(xml_FilePath);
            //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://120.27.210.156:8989/import.asp");///这是旭乐基的eai网址
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://192.168.233.128:8989/import.asp");
            myRequest.Method = "POST";
            myRequest.ContentType = @"text/xml;charset=utf-8";
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            xmlDoc.Save(ms);
            byte[] bytes = ms.ToArray();
            myRequest.ContentLength = bytes.Length;
            System.IO.Stream s = myRequest.GetRequestStream();
            s.Write(bytes, 0, bytes.Length);
            s.Close();
            System.IO.StreamReader sr = new System.IO.StreamReader(myRequest.GetResponse().GetResponseStream());
            String retXml = sr.ReadToEnd();
            sr.Close();
            string path = "导入结果.txt";//文件存放路径，保证文件存在。
            StreamWriter sw = new StreamWriter(path, true);
            sw.WriteLine(retXml);
            sw.Close();


            ///显示入库单号码
            sql = "select rdrecord10.ccode from rdrecord10 join rdrecords10 on rdrecord10.ID =rdrecords10.ID ";
            sql += " where cdefine31 ='" + 报工id + "'";
            DataTable tb3 = pub.U8GetTable(sql);
            if (tb3.Rows.Count > 0)
            {
                ///改写本次入库数量到最后顺序的报工数
                if (本次入库数量 != pub.ToDecimal(tb1.Rows[0]["报工数量"].ToString()))
                {
                    sql = "update z_baogong set 报工数量 ='" + 本次入库数量 + "' where id='" + 报工id + "'";
                    pub.ExcuteSql(sql, "根据入库数量改写最后顺序的报工数");

                }

                string sql2 = "update rdrecord10 set rdrecord10.cMPoCode='" + 生产加工单号 + "'   ";
                sql2 += " from rdrecord10,rdrecords10  ";
                sql2 += " where rdrecord10.id=rdrecords10.id  ";
                sql2 += "and rdrecords10.cdefine31 ='" + 报工id + "' ";
                pub.ExcuteSql(sql2, "更新产成品入库单表头生产订单号");

                string sqlcsource = "update rdrecord10 set rdrecord10.csource='生产订单'   ";
                sqlcsource += " from rdrecord10,rdrecords10  ";
                sqlcsource += " where rdrecord10.id=rdrecords10.id  ";
                sqlcsource += "and rdrecords10.cdefine31 ='" + 报工id + "' ";
                pub.ExcuteSql(sqlcsource, "更新产成品入库单表头生产订单号");

                //cmocode
                string sqlhang = "update rdrecords10 set rdrecords10.imoseq='" + 生产子表id + "'   ";
                sqlhang += " from rdrecord10,rdrecords10  ";
                sqlhang += " where rdrecord10.id=rdrecords10.id  ";
                sqlhang += "and rdrecords10.cdefine31 ='" + 报工id + "' ";
                pub.ExcuteSql(sqlhang, "更新产成品入库单表身生产订单行号");

                string sqlschang = "update rdrecords10 set rdrecords10.cmocode='" + 生产加工单号 + "'   ";
                sqlschang += " from rdrecord10,rdrecords10  ";
                sqlschang += " where rdrecord10.id=rdrecords10.id  ";
                sqlschang += "and rdrecords10.cdefine31 ='" + 报工id + "' ";
                pub.ExcuteSql(sqlschang, "更新产成品入库单表身生产订单行号");

                //回写完成数
                string sqlrukushu = "select sum(iquantity) 入库数 from rdrecords10 join rdrecord10 on rdrecord10.id=rdrecords10.id where rdrecord10.cMPoCode = '" + 生产加工单号 + "' ";
                sqlrukushu += " and rdrecords10.imoseq='" + 生产子表id + "' ";
                DataTable tbrukushu = pub.U8GetTable(sqlrukushu);
                if (tbrukushu.Rows.Count > 0)
                {
                    string 完成数 = tbrukushu.Rows[0]["入库数"].ToString();

                    string sqlhuixie = "update mom_orderdetail set mom_orderdetail.QualifiedInQty='" + 完成数 + "'   ";
                    sqlhuixie += " from mom_orderdetail,mom_order  ";
                    sqlhuixie += " where mom_orderdetail.moid=mom_order.moid  ";
                    sqlhuixie += "and  mom_order.mocode ='" + 生产加工单号 + "' and  mom_orderdetail.SortSeq= '" + 生产子表id + "'";
                    pub.ExcuteSql(sqlhuixie, "回写完成数");

                }

                return tb3.Rows[0][0].ToString();
            }
            else
            {
                return "";
            }

        }

        //检查现存量是否足够
        private bool checkCurrentStock(string 物料编号, decimal 本次入库数量)
        {
            string message = "现存量不足：" + "\r\n";
            DataRow[] drsBomId = dataTableGYLX.Select("cInvCode = '" + 物料编号 + " '");
            if (drsBomId != null && drsBomId.Length == 1)
            {
                DataRow[] drsBaseQtyN = dataTableBasQuantity.Select("BomId = '" + drsBomId[0]["BomId"].ToString() + "'");
                for (int i = 0; i < drsBaseQtyN.Length; i++)
                {
                    decimal 实际需要数量 = 本次入库数量 * pub.ToDecimal(drsBaseQtyN[i]["BaseQtyN"].ToString());

                    if (dataTableCurrentStock.Select("cInvCode = '" + drsBaseQtyN[i]["InvCode"].ToString() + "'").Length > 0)
                    {
                        decimal 现存量 = pub.ToDecimal(dataTableCurrentStock.Select("cInvCode = '" + drsBaseQtyN[i]["InvCode"].ToString() + "'")[0]["iQuantity"].ToString());
                        if (实际需要数量 > 现存量)
                        {
                            message += drsBaseQtyN[i]["InvCode"].ToString() + "--" + drsBaseQtyN[i]["cInvName"].ToString() + "  现存量为： " + 现存量 + "  实际需求量为：  " + 实际需要数量 + "\r\n";
                        }
                    }
                    else
                    {
                        message += "现存量中没有该物料数据： " + drsBaseQtyN[i]["InvCode"].ToString() + "--" + drsBaseQtyN[i]["cInvName"].ToString();
                    }
                }
            }
            if (!message.Equals("现存量不足：" + "\r\n"))
            {
                FormCurrentStockError formCurrentStock = new FormCurrentStockError(message);
                formCurrentStock.Show();
                return false;
            }
            else
            {
                return true;
            }

            //string message = "现存量不足：" +"\r\n";
            //string sqlBomID = @"select bom_bom.BomId,Inventory.cInvCode
            //            from bom_parent
            //            left join bom_bom on bom_parent.BomId = bom_bom.BomId
            //            left join bas_part on bas_part.PartId = bom_parent.ParentId
            //            left join Inventory on bas_part.InvCode = Inventory.cInvCode
            //            left join ComputationUnit on Inventory.cComUnitCode = ComputationUnit.cComunitCode";
            ////            where Inventory.cInvCode = '";
            ////sqlBomID += 物料编号 + "'";
            //DataTable dt = pub.U8GetTable(sqlBomID);
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    string bomId = dt.Rows[0]["BomId"].ToString();//获取BOMID

            //    string sqlBomBody = @"select bas_part.InvCode,Inventory.cInvName,Inventory.cInvAddCode,bom_opcomponent.BaseQtyN,Warehouse.cWhCode,Warehouse.cWhName
            //                    from bom_bom left join bom_opcomponent on bom_bom.BomId = bom_opcomponent.BomId
            //                    left join bas_part on bom_opcomponent.ComponentId = bas_part.PartId
            //                    left join Inventory on bas_part.InvCode = Inventory.cInvCode
            //                    left join ComputationUnit on Inventory.cComUnitCode = ComputationUnit.cComunitCode
            //                    left join Warehouse on Inventory.cDefWareHouse = Warehouse.cWhCode
            //                    where cWhCode = '0402' and bom_opcomponent.BomId = '" + bomId + "'";
            //    DataTable dtBomBody = pub.U8GetTable(sqlBomBody);//获取子件明细

            //    if (dtBomBody != null && dtBomBody.Rows.Count > 0)
            //    {
            //        //检查现存量与入库所需量做对比
            //        for (int i = 0; i < dtBomBody.Rows.Count; i++)
            //        {
            //            decimal 实际需要数量 = 本次入库数量 * pub.ToDecimal(dtBomBody.Rows[i]["BaseQtyN"].ToString());
            //            string sql = "select ISNULL(iQuantity,0) iQuantity from CurrentStock where cInvCode = '" + dtBomBody.Rows[i]["InvCode"].ToString() + "'";
            //            DataTable currentStock = pub.U8GetTable(sql);
            //            if (currentStock != null && currentStock.Rows.Count > 0 && pub.ToDecimal(currentStock.Rows[0][0].ToString()) < 实际需要数量)
            //            {
            //                message += dtBomBody.Rows[i]["cInvName"].ToString() + "  现存量为： " + pub.ToDecimal(currentStock.Rows[0][0].ToString()) + "  实际需求量为：  " + 实际需要数量 + "\r\n";
            //            }
            //        }
            //    }

            //}
            //if (!"现存量不足：".Equals(message))
            //{
            //    FormCurrentStockError formCurrentStock = new FormCurrentStockError(message);
            //    formCurrentStock.Show();
            //    return false;
            //}
            //else
            //{
            //    return true;
            //}
        }
        private string Get计量单位(string 存货编号)
        {

            string sql;
            sql = "select cDefWareHouse  from  Inventory join  where cinvcode='" + 存货编号 + "' ";
            DataTable tb = pub.U8GetTable(sql);
            if (tb.Rows.Count > 0)
            {
                return tb.Rows[0][0].ToString();
            }
            else
            {
                return "0501";///成品仓库
            }
        }
        /// <summary>
        /// 获得主储仓库
        /// </summary>
        /// <param name="存货编号"></param>
        /// <returns></returns>
        private string Get仓库编号(string 存货编号)
        {
            string sql;
            sql = "select cDefWareHouse  from  Inventory where cinvcode='" + 存货编号 + "' ";
            DataTable tb = pub.U8GetTable(sql);
            if (tb.Rows.Count > 0)
            {
                if (tb.Rows[0][0].ToString() != "")
                {
                    return tb.Rows[0][0].ToString();
                }
                else
                {
                    return "0501";///成品仓库
                }
            }
            else
            {
                return "0501";///成品仓库
            }
        }
        private string Get出库单号(string date)
        {
            string sql = @"select isnull(max(cCode),0) cCode from rdrecord11 where dDate = '" + date + "'";
            DataTable dt = pub.U8GetTable(sql);
            if (dt != null && dt.Rows.Count > 0 && !"0".Equals(dt.Rows[0]["cCode"].ToString()))
            {
                return (double.Parse(dt.Rows[0]["cCode"].ToString()) + 1).ToString();
            }
            else
            {
                return DateTime.Parse(date).ToString("yyyyMMdd") + "0001";
            }
        }
        private string Get入库单号()
        {
            string sql;
            string 单号;
            sql = "select isnull(max (convert(bigint,[cCode])),0) from [rdrecord10] ";
            DataTable tb = pub.U8GetTable(sql);
            if (tb != null)
            {
                单号 = (pub.ToNum(tb.Rows[0][0].ToString()) + 1).ToString().PadLeft(10, '0');
            }
            else
            {
                单号 = "0000000001";
            }
            return 单号;
        }

        private bool Is已经导入到U8(int 报工id)
        {
            string sql;
            sql = "select * from rdrecords10 where cDefine31='" + 报工id + "'";
            DataTable tb = pub.U8GetTable(sql);
            if (tb.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }






        public static void Get_DRJieguo()
        {
            System.Xml.XmlDocument dom = new XmlDocument();
            //string T6IP = System.Configuration.ConfigurationSettings.AppSettings["T6IP"].ToString();
            //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(T6IP);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://120.27.210.156:8989/import.asp");///这是旭乐基的eai网址
            myRequest.Method = "POST";
            myRequest.ContentType = @"text/xml;charset=utf-8";
            dom.Load("StoreInOut.Xml");////
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            dom.Save(ms);
            byte[] bytes = ms.ToArray();
            myRequest.ContentLength = bytes.Length;
            System.IO.Stream s = myRequest.GetRequestStream();
            s.Write(bytes, 0, bytes.Length);
            s.Close();
            System.IO.StreamReader sr = new System.IO.StreamReader(myRequest.GetResponse().GetResponseStream());
            String retXml = sr.ReadToEnd();
            sr.Close();
            string path = "导入结果.txt";//文件存放路径，保证文件存在。
            StreamWriter sw = new StreamWriter(path, true);
            sw.WriteLine(retXml);
            sw.Close();


        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form fm = new FormClly();
            fm.Show();
        }


    }
}
